<template>
  <div class="user-list-container">
    <div class="search-panel">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户账号">
          <el-input v-model="searchForm.username" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="用户姓名">
          <el-input v-model="searchForm.nickname" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="searchForm.phone" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.createTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-panel">
      <div class="table-header">
        <div class="table-title">用户列表</div>
        <div class="table-actions">
          <el-button-group>
            <el-button size="small" @click="handleExport">
              <el-icon><Download /></el-icon> 导出
            </el-button>
            <el-button size="small" @click="handleImport">
              <el-icon><Upload /></el-icon> 导入
            </el-button>
          </el-button-group>
          <el-button type="primary" size="small" @click="handleAdd">
            <el-icon><Plus /></el-icon> 新增
          </el-button>
        </div>
      </div>

      <el-table
        :data="userList"
        border
        style="width: 100%"
        v-loading="loading"
        :header-cell-style="{background:'#f5f7fa', color:'#606266'}"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="name" label="名称" min-width="120"></el-table-column>
        <el-table-column prop="title" label="职称" min-width="150"></el-table-column>
        <el-table-column label="头像" width="70">
          <template #default="scope">
            <el-avatar :size="40" :src="scope.row.avatar" v-if="scope.row.avatar">
              {{ scope.row.name?.substring(0, 1) }}
            </el-avatar>
            <el-avatar :size="40" v-else>{{ scope.row.name?.substring(0, 1) }}</el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="department" label="部门" min-width="120"></el-table-column>
        <el-table-column prop="phone" label="手机号" min-width="120"></el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="(val) => handleStatusChange(scope.row, val)"
              active-color="#13ce66"
              inactive-color="#ff4949"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160"></el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            <el-dropdown trigger="click">
              <el-button link type="primary" size="small">更多</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleResetPassword(scope.row)">重置密码</el-dropdown-item>
                  <el-dropdown-item @click="handleAssignRole(scope.row)">分配角色</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 30, 50]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          small
        ></el-pagination>
      </div>
    </div>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formMode === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
      destroy-on-close
    >
      <el-form
        :model="userForm"
        :rules="userFormRules"
        ref="userFormRef"
        label-width="80px"
        status-icon
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="formMode === 'edit'"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name"></el-input>
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-input v-model="userForm.title"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="departmentId">
          <el-tree-select
            v-model="userForm.departmentId"
            :data="departmentOptions"
            check-strictly
            node-key="id"
            :props="{
              label: 'name',
              children: 'children',
              value: 'id'
            }"
            placeholder="请选择部门"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="formMode === 'add'">
          <el-input v-model="userForm.password" type="password" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog v-model="roleDialogVisible" title="分配角色" width="500px" destroy-on-close>
      <el-transfer
        v-model="selectedRoles"
        :data="roleOptions"
        :titles="['可选角色', '已选角色']"
        :props="{
          key: 'id',
          label: 'name'
        }"
      ></el-transfer>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRoleAssign" :loading="roleSubmitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Download, Upload, Plus } from '@element-plus/icons-vue'
import { 
  getUserList, 
  getUserById, 
  addUser, 
  updateUser, 
  deleteUser, 
  resetPassword, 
  updateUserStatus, 
  assignRoles, 
  getUserRoleIds 
} from '@/api/user'
import { getDepartmentTree } from '@/api/department'
import { getAllRoles } from '@/api/auth'

// 状态
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const formMode = ref('add')
const roleDialogVisible = ref(false)
const roleSubmitLoading = ref(false)

// 搜索表单
const searchForm = reactive<{
  username: string;
  nickname: string;
  phone: string;
  createTime: string[];
}>({
  username: '',
  nickname: '',
  phone: '',
  createTime: []
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 用户表单
const userFormRef = ref<FormInstance>()
const userForm = reactive<{
  id: number | undefined;
  username: string;
  name: string;
  title: string;
  phone: string;
  departmentId: number | undefined;
  status: number;
  password: string;
  email: string;
}>({
  id: undefined,
  username: '',
  name: '',
  title: '',
  phone: '',
  departmentId: undefined,
  status: 1,
  password: '',
  email: ''
})

// 表单规则
const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  departmentId: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  password: [
    { required: formMode.value === 'add', message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6个字符', trigger: 'blur' }
  ]
}

// 数据源
const userList = ref<any[]>([])
const departmentOptions = ref<any[]>([])
const roleOptions = ref<any[]>([])
const selectedRoles = ref<number[]>([])

// 创建时间范围处理
const dateRange = computed(() => {
  if (searchForm.createTime && searchForm.createTime.length === 2) {
    return {
      startDate: searchForm.createTime[0],
      endDate: searchForm.createTime[1]
    }
  }
  return {
    startDate: undefined,
    endDate: undefined
  }
})

// 生命周期钩子
onMounted(() => {
  fetchUserList()
  fetchDepartmentTree()
  fetchRoleOptions()
})

// 获取用户列表
const fetchUserList = () => {
  loading.value = true
  getUserList({
    current: pagination.current,
    size: pagination.size,
    username: searchForm.username || undefined,
    nickname: searchForm.nickname || undefined,
    phone: searchForm.phone || undefined,
    startDate: dateRange.value.startDate,
    endDate: dateRange.value.endDate
  })
    .then(res => {
      if (res && res.data) {
        userList.value = res.data.records || []
        pagination.total = res.data.total || 0
      }
    })
    .catch(error => {
      console.error('获取用户列表失败', error)
      ElMessage.error('获取用户列表失败')
    })
    .finally(() => {
      loading.value = false
    })
}

// 获取部门树
const fetchDepartmentTree = () => {
  getDepartmentTree()
    .then(res => {
      if (res && res.data) {
        departmentOptions.value = res.data
      }
    })
    .catch(error => {
      console.error('获取部门树失败', error)
      ElMessage.error('获取部门树失败')
    })
}

// 获取角色选项
const fetchRoleOptions = () => {
  getAllRoles()
    .then(res => {
      if (res && res.data) {
        roleOptions.value = res.data.map((role: any) => ({
          id: role.id,
          name: role.roleName
        }))
      }
    })
    .catch(error => {
      console.error('获取角色列表失败', error)
      ElMessage.error('获取角色列表失败')
    })
}

// 搜索操作
const handleSearch = () => {
  pagination.current = 1
  fetchUserList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    if (key === 'createTime') {
      searchForm[key] = [];
    } else {
      searchForm[key as keyof typeof searchForm] = '';
    }
  })
  handleSearch()
}

// 分页操作
const handleSizeChange = (size: number) => {
  pagination.size = size
  fetchUserList()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchUserList()
}

// 添加用户
const handleAdd = () => {
  formMode.value = 'add'
  Object.keys(userForm).forEach(key => {
    const k = key as keyof typeof userForm;
    if (k === 'status') {
      userForm[k] = 1;
    } else if (k === 'id' || k === 'departmentId') {
      userForm[k] = undefined;
    } else {
      userForm[k] = '';
    }
  })
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row: any) => {
  formMode.value = 'edit'
  getUserById(row.id)
    .then(res => {
      if (res && res.data) {
        const userData = res.data
        userForm.id = userData.id
        userForm.username = userData.username
        userForm.name = userData.name || userData.nickname
        userForm.title = userData.title
        userForm.phone = userData.phone || ''
        userForm.email = userData.email || ''
        userForm.departmentId = userData.departmentId
        userForm.status = userData.status
      }
      dialogVisible.value = true
    })
    .catch(error => {
      console.error('获取用户详情失败', error)
      ElMessage.error('获取用户详情失败')
    })
}

// 删除用户
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除用户 ${row.name} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteUser(row.id)
      .then(() => {
        ElMessage.success('删除成功')
        fetchUserList()
      })
      .catch(error => {
        console.error('删除用户失败', error)
        ElMessage.error('删除用户失败')
      })
  }).catch(() => {})
}

// 状态变更
const handleStatusChange = (row: any, value: number) => {
  updateUserStatus(row.id, value)
    .then(() => {
      const statusText = value === 1 ? '启用' : '禁用'
      ElMessage.success(`已${statusText}用户${row.name}`)
    })
    .catch(error => {
      console.error('更新用户状态失败', error)
      ElMessage.error('更新用户状态失败')
      row.status = value === 1 ? 0 : 1  // 恢复UI状态
    })
}

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate((valid, fields) => {
    if (valid) {
      submitLoading.value = true
      
      const apiCall = formMode.value === 'add' 
        ? addUser({
            username: userForm.username,
            password: userForm.password,
            name: userForm.name,
            title: userForm.title,
            phone: userForm.phone,
            email: userForm.email,
            departmentId: userForm.departmentId,
            status: userForm.status
          })
        : updateUser({
            id: userForm.id,
            name: userForm.name,
            title: userForm.title,
            phone: userForm.phone,
            email: userForm.email,
            departmentId: userForm.departmentId,
            status: userForm.status
          })
      
      apiCall
        .then(() => {
          ElMessage.success(formMode.value === 'add' ? '添加成功' : '更新成功')
          dialogVisible.value = false
          fetchUserList()
        })
        .catch(error => {
          console.error(formMode.value === 'add' ? '添加用户失败' : '更新用户失败', error)
          ElMessage.error(formMode.value === 'add' ? '添加用户失败' : '更新用户失败')
        })
        .finally(() => {
          submitLoading.value = false
        })
    }
  })
}

// 根据部门ID获取部门名称
const getDepartmentNameById = (id: number | undefined) => {
  if (!id) return ''
  
  // 递归查找部门
  const findDepartment = (departments: any[], targetId: number): string => {
    for (const dept of departments) {
      if (dept.id === targetId) {
        return dept.name
      }
      if (dept.children && dept.children.length) {
        const found = findDepartment(dept.children, targetId)
        if (found) return found
      }
    }
    return ''
  }
  
  return findDepartment(departmentOptions.value, id)
}

// 分配角色相关
const currentUserId = ref<number>(0)

const handleAssignRole = (row: any) => {
  currentUserId.value = row.id
  roleDialogVisible.value = true
  
  // 获取用户已分配的角色
  getUserRoleIds(row.id)
    .then(res => {
      if (res && res.data) {
        selectedRoles.value = res.data
      }
    })
    .catch(error => {
      console.error('获取用户角色失败', error)
      ElMessage.error('获取用户角色失败')
    })
}

const submitRoleAssign = () => {
  roleSubmitLoading.value = true
  
  assignRoles(currentUserId.value, selectedRoles.value)
    .then(() => {
      ElMessage.success('角色分配成功')
      roleDialogVisible.value = false
    })
    .catch(error => {
      console.error('分配角色失败', error)
      ElMessage.error('分配角色失败')
    })
    .finally(() => {
      roleSubmitLoading.value = false
    })
}

// 重置密码
const handleResetPassword = (row: any) => {
  ElMessageBox.confirm(`确定要重置 ${row.name} 的密码吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    resetPassword(row.id)
      .then(() => {
        ElMessage.success(`已重置用户 ${row.name} 的密码为: 123456`)
      })
      .catch(error => {
        console.error('重置密码失败', error)
        ElMessage.error('重置密码失败')
      })
  }).catch(() => {})
}

// 导入导出
const handleExport = () => {
  ElMessage.success('导出功能待实现')
}

const handleImport = () => {
  ElMessage.info('导入功能待实现')
}
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.search-panel {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.table-panel {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-transfer-panel) {
  width: 220px;
}
</style>